/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jee.forum.controller;

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import jee.forum.entities.Category;
import jee.forum.entities.Forum;
import jee.forum.entities.Topic;
import org.apache.log4j.Logger;

/**
 *
 * @author Tobi
 */
@Stateless
public class CategoryController {

    @PersistenceContext
    private EntityManager em;
    Logger log = Logger.getLogger(CategoryController.class);

    public void createCategory(String name, String description, Forum forum) throws Exception {
        log.info("Create new Category: " + name);

        Category category = new Category(name, description, forum);

        em.persist(category);
    }

    public Category getCategoryById(int id) {
        Category category = em.find(Category.class, id);
        return category;
    }

    public Category getCategoryByName(String name){
         Query q = em.createNamedQuery("category.ByName");
         q.setParameter("name", name);
         Category category = (Category) q.getSingleResult();
         
         
         Query qu = em.createNamedQuery("Topic.ForCategoryId");
         q.setParameter("categoryId", category.getId());
         List<Topic> topics = q.getResultList();

         for(Topic t : topics){
            category.addTopic(t);
         }

         return category;
    }
}
